package top.suven.base.http.admin.log.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.suven.base.core.mybatis.PageData;
import top.suven.base.core.redis.RedisClusterServer;
import top.suven.base.core.redis.RedisConstants;
import top.suven.base.core.redis.RedisKeys;
import top.suven.base.http.admin.log.dao.LoginLogWebDao;
import top.suven.base.http.admin.log.model.LoginInfo;
import top.suven.base.http.admin.log.model.LoginLog;
import top.suven.base.http.admin.log.service.LoginLogWebService;
import top.suven.base.http.admin.log.vo.response.LoginClientLog;
import top.suven.base.http.admin.log.vo.response.LoginLogResponseVo;
import top.suven.base.http.admin.user.model.UserReport;
import top.suven.base.http.enums.EnableStatusEnum;
import top.suven.base.util.utilize.BeanUtil;
import top.suven.base.util.utilize.JsonUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: LoginLogWebServiceImpl.java
 * @Description: 登录日志的业务处理服务类
 * @author lixiangling
 * @date   2018/08/28 11:12:22
 * @version V1.0.0
 * ----------------------------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 * ----------------------------------------------------------------------------
 *
 */
@Component("loginLogWebService")
public class LoginLogWebServiceImpl implements LoginLogWebService {
    private final static Logger logger = LoggerFactory.getLogger(LoginLogWebServiceImpl.class);
    @Autowired
    private LoginLogWebDao loginLogWebDao;
    @Autowired
    private RedisClusterServer redisClusterServer;
//    @Autowired
//    private CommWebService commWebService;
    /**
     * @Title: 获取登录日志分页信息
     * @Description:
     * @param loginLog @{Link LoginLog}
     * @return
     * @throw
     * @author lixiangling
     * @date 2018/08/28 11:12:22
     *  --------------------------------------------------------
     *  modifyer    modifyTime                 comment
     *
     *  --------------------------------------------------------
     */
    public PageData<LoginLogResponseVo> getLoginLogPage(LoginLog loginLog, int start, int pageSize){
        int count = loginLogWebDao.countEntity(loginLog);
        if(count == 0){
            return new PageData<LoginLogResponseVo>(Collections.EMPTY_LIST,count);
        }
        List<LoginLog> loginLogList = loginLogWebDao.findPageEntity(loginLog, start, pageSize);
        if(loginLogList == null || loginLogList.isEmpty()){
            return new PageData<LoginLogResponseVo>(Collections.EMPTY_LIST,count);
        }
        List<LoginLogResponseVo> loginLogResponseList = loginLogList.stream().map(loginLogResponse -> {
            LoginLogResponseVo loginLogResponseVo = new LoginLogResponseVo();
            BeanUtil.copyProperties(loginLogResponse, loginLogResponseVo);
            return loginLogResponseVo;
        }).collect(Collectors.toList());
        return new PageData<LoginLogResponseVo>(loginLogResponseList,count);
    }
    /**
     * @Title: 获取登录日志列表信息
     * @Description:
     * @param loginLog @{Link LoginLog}
     * @return
     * @throw
     * @author lixiangling
     * @date 2018/08/28 11:12:22
     *  --------------------------------------------------------
     *  modifyer    modifyTime                 comment
     *
     *  --------------------------------------------------------
     */
    public List<LoginLog> getLoginLogList(LoginLog loginLog){
        return loginLogWebDao.findEntity(loginLog);
    }

    /**
     * @Title: 新增登录日志信息
     * @Description:
     * @param loginLog @{Link LoginLog}
     * @return
     * @throw
     * @author lixiangling
     * @date 2018/08/28 11:12:22
     *  --------------------------------------------------------
     *  modifyer    modifyTime                 comment
     *
     *  --------------------------------------------------------
     */
    public void addLoginLog(LoginLog loginLog){
        loginLogWebDao.createEntity(loginLog);
    }
    /**
    * @Title: 修改登录日志信息
    * @Description:
    * @param loginLog @{Link LoginLog}
    * @return
    * @throw
    * @author lixiangling
    * @date 2018/08/28 11:12:22
    *  --------------------------------------------------------
    *  modifyer    modifyTime                 comment
    *
    *  --------------------------------------------------------
    */
    public void updLoginLog(LoginLog loginLog){
        loginLogWebDao.updateEntity(loginLog);
    }
   /**
    * @Title: 获取登录日志信息
    * @Description:
    * @param id @{Link Long}
    * @return
    * @throw
    * @author lixiangling
    * @date 2018/08/28 11:12:22
    *  --------------------------------------------------------
    *  modifyer    modifyTime                 comment
    *
    *  --------------------------------------------------------
    */
    public LoginLog getLoginLog(Long id){
        LoginLog loginLog = new LoginLog();
        loginLog.setLogId(id);
        return loginLogWebDao.retrieveEntity(loginLog);
    }
    /**
     * @Title: 删除登录日志信息
     * @Description:
     * @param ids @{Link Long[]}
     * @return
     * @throw
     * @author lixiangling
     * @date 2018/08/28 11:12:22
     *  --------------------------------------------------------
     *  modifyer    modifyTime                 comment
     *
     *  --------------------------------------------------------
     */
    public void del(Long[] ids){
        loginLogWebDao.del(Arrays.asList(ids));
    }
   /**
    * @Title: 启用登录日志信息
    * @Description:
    * @param ids @{Link Long[]}
    * @return
    * @throw
    * @author lixiangling
    * @date 2018/08/28 11:12:22
    *  --------------------------------------------------------
    *  modifyer    modifyTime                 comment
    *
    *  --------------------------------------------------------
    */
    public void turnOn(Long[] ids){
        loginLogWebDao.updateEnableStatus(EnableStatusEnum.ENABLE.getIndexStr(), Arrays.asList(ids));
    }
   /**
    * @Title: 禁用登录日志信息
    * @Description:
    * @param ids @{Link Long[]}
    * @return
    * @throw
    * @author lixiangling
    * @date 2018/08/28 11:12:22
    *  --------------------------------------------------------
    *  modifyer    modifyTime                 comment
    *
    *  --------------------------------------------------------
    */
    public void turnOff(Long[] ids){
        loginLogWebDao.updateEnableStatus(EnableStatusEnum.DISABLE.getIndexStr(), Arrays.asList(ids));
    }

    /**
     * @Title: 获取用户一周的登录信息
     * @Description:
     * @param
     * @return
     * @throw
     * @author lixiangling
     * @date 2018/8/28 16:28
     *  --------------------------------------------------------
     *  modifyer    modifyTime                 comment
     *
     *  --------------------------------------------------------
     */
    public LoginClientLog getLoginInfoClient() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String now = format.format(new Date());
        LoginClientLog loginClientLog = new LoginClientLog();
        String registerInfo = redisClusterServer.get(String.format("%s%s", RedisKeys.LOG_LOGIN_CLIENT_INFO, now));
        if(StringUtils.isNotBlank(registerInfo)){
            return JsonUtils.readValue(registerInfo, LoginClientLog.class);
        }
        List<LoginInfo> loginInfoList = loginLogWebDao.getLoginInfoClient();
        if(loginInfoList == null || loginInfoList.isEmpty()){
            return loginClientLog;
        }
        loginClientLog.setClientTypes(new String[loginInfoList.size()]);
        List<UserReport> userReports = new ArrayList<>();
        for(int i=0,length=loginInfoList.size();i<length;i++){
            LoginInfo loginInfo = loginInfoList.get(i);
            // todo
//            String clientType = commWebService.getClientType(loginInfo.getClientType());
//            loginClientLog.getClientTypes()[i] = clientType;
//
//            UserReport userReport = new UserReport();
//            userReport.setName(clientType);
//            userReport.setValue(loginInfo.getCount());
//            userReports.add(userReport);
        }
        loginClientLog.setReports(userReports);
        redisClusterServer.setex(String.format("%s%s", RedisKeys.LOG_LOGIN_CLIENT_INFO, now),JsonUtils.toJsonString(loginClientLog), RedisConstants.ONE_DAY);
        return loginClientLog;
    }

    @Override
    public LoginClientLog getLoginInfoRateOfRise() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String now = format.format(new Date());
        LoginClientLog loginClientLog = new LoginClientLog();
        String registerInfo = redisClusterServer.get(String.format("%s%s", RedisKeys.LOG_LOGIN_STATISTIC_INFO, now));
        if(StringUtils.isNotBlank(registerInfo)){
            return JsonUtils.readValue(registerInfo, LoginClientLog.class);
        }
        List<LoginInfo> loginInfoList = loginLogWebDao.getLoginInfoRateOfRise();
        if(loginInfoList == null || loginInfoList.isEmpty()){
            return loginClientLog;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE,-2);
        String beforeYesterDay = format.format(calendar.getTime());
        calendar.add(Calendar.DATE,1);
        String yesterday = format.format(calendar.getTime());

        for(LoginInfo loginInfo : loginInfoList){
            if(beforeYesterDay.equals(loginInfo.getLoginTime())){
                loginClientLog.setBeforeYesterdayCount(loginInfo.getCount());
            }else if(yesterday.equals(loginInfo.getLoginTime())){
                loginClientLog.setYesterdayCount(loginInfo.getCount());
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("##.##");
        //安卓环比
        loginClientLog.setRateOfRise(Float.parseFloat(decimalFormat.format( (loginClientLog.getYesterdayCount()-loginClientLog.getBeforeYesterdayCount())/
                (loginClientLog.getBeforeYesterdayCount()==0?1f:loginClientLog.getBeforeYesterdayCount()))));
        redisClusterServer.setex(String.format("%s%s", RedisKeys.LOG_LOGIN_STATISTIC_INFO, now),JsonUtils.toJsonString(loginClientLog), RedisConstants.ONE_DAY);
        return loginClientLog;
    }
}